<template>
  <div class="post-detail-container">
    <!-- 导航栏 - 修改为单一导航栏 -->
    <div class="post-header">
      <div class="header-content">
        <div class="header-left">
          <div class="logo">
            <img src="@/assets/logo.png" alt="灵图logo" class="logo-img" @click="goHome" />
          </div>

          <div class="breadcrumb">
            <h1 class="community-name">{{ postVO?.communityName || '灵图公社' }}</h1>
            <a-breadcrumb>
              <a-breadcrumb-item>
                <router-link to="/">首页</router-link>
              </a-breadcrumb-item>
              <a-breadcrumb-item>
                <router-link to="/community">社区</router-link>
              </a-breadcrumb-item>
              <a-breadcrumb-item>文章详情</a-breadcrumb-item>
            </a-breadcrumb>
          </div>
        </div>
        <div class="header-right">
          <RouterLink to="/community/createPost">
            <a-button class="submit-button">
              <edit-outlined />
              写文章
            </a-button>
          </RouterLink>
          <div class="user-info">
            <a-avatar :src="postVO?.userAvatar || '/default-avatar.png'" class="user-avatar" />
            <span class="user-name">{{ postVO?.userName }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 主体内容区 -->
    <div class="post-content">
      <!-- 左侧互动数据 -->
      <div class="post-stats">
        <div class="post-stats-sticky">
          <div class="stat-item" @click="handleLike">
            <like-outlined :class="{ liked: isLiked }" />
            <span class="stat-value">{{ postVO?.likeCount || 0 }}</span>
            <span class="stat-label">点赞</span>
          </div>
          <div class="stat-item">
            <eye-outlined />
            <span class="stat-value">{{ postVO?.viewCount || 0 }}</span>
            <span class="stat-label">浏览</span>
          </div>
          <div class="stat-item" @click="scrollToComments">
            <message-outlined />
            <span class="stat-value">{{ postVO?.commentCount || 0 }}</span>
            <span class="stat-label">评论</span>
          </div>
          <div class="stat-item" @click="handleFavorite">
            <star-outlined :class="{ favorited: userFavorited }" />
            <span class="stat-value">{{ postVO?.favourCount || 0 }}</span>
            <span class="stat-label">收藏</span>
          </div>
        </div>
      </div>

      <!-- 中间文章内容 -->
      <div class="post-main">
        <div class="post-top">
          <span class="post-top-intro"> {{ postVO?.communityName || '灵图公社' }} > </span>
          <span class="post-top-intro"> {{ postVO?.title }} </span>
          <img
            v-if="postVO?.imageUrl"
            :src="postVO?.imageUrl"
            class="post-image"
            alt="post image"
          />
        </div>

        <div class="post-title">{{ postVO?.title }}</div>
        <div class="post-summary">
          {{ postVO?.summary }}
        </div>
        <div class="post-author">
          <img
            :src="postVO?.userAvatar || '/default-avatar.png'"
            class="avatar"
            alt="user avatar"
          />
          <div class="author-info">
            <div class="author-name">{{ postVO?.userName }}</div>
            <div class="post-meta">
              <span class="post-time">{{ formatDate(postVO?.createTime) }}</span>
              <span class="post-views"><eye-outlined /> {{ postVO?.viewCount || 0 }}</span>
            </div>
          </div>
        </div>

        <!-- 文章内容处理 -->
        <div class="post-body" v-if="postVO?.content">
          <!-- 使用v-html渲染富文本内容 -->
          <div class="content-html" v-if="isHtmlContent" v-html="postVO.content"></div>
          <!-- 使用Markdown渲染 -->
          <div
            class="content-markdown"
            v-else-if="isMarkdownContent"
            v-html="renderedMarkdown"
          ></div>
          <!-- 使用pre标签渲染纯文本内容，保留换行和格式 -->
          <pre class="content-text" v-else>{{ postVO.content }}</pre>
        </div>
        <!-- 评论区 -->
        <a-divider/>
        <div ref="commentsRef">
          <comment-section :post-id="props.id" @comment-added="handleCommentAdded" @comment-deleted="handleCommentDeleted"/>
        </div>
      </div>

      <!-- 右侧作者信息和其他文章 -->
      <div class="post-sidebar">
        <div class="author-card">
          <img
            :src="postVO?.userAvatar || '/default-avatar.png'"
            class="avatar-large"
            alt="user avatar"
          />
          <div class="author-details">
            <div class="author-name-large">{{ postVO?.userName }}</div>
            <div class="author-bio">{{ postVO?.userProfile }}</div>
            <div class="author-stats">
              <div class="stat">
                <span class="stat-value">{{ postVO?.postNumber }}篇</span>
                <span class="stat-label">文章</span>
              </div>
              <div class="stat">
                <span class="stat-value">2.5k</span>
                <span class="stat-label">粉丝</span>
              </div>
            </div>
            <a-button v-if="loginUser?.id !== postVO?.userId" type="primary" class="follow-btn"
              >关注</a-button
            >
          </div>
        </div>

        <div class="related-posts">
          <h3>作者的其他文章</h3>
          <div class="post-list">
            <div class="related-post-item" v-for="item in postVO?.postDetailVOList" :key="item.id" @click="handlePostClick(item.id || 0)">
              <div  class="post-other-title">{{ item?.title }}</div>
              <div class="post-meta">
                <span class="post-time">{{ formatDate(item?.createTime) }}</span>
                <span class="post-views"><eye-outlined />{{ item?.likeCount }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  LikeOutlined,
  EyeOutlined,
  MessageOutlined,
  StarOutlined,
  EditOutlined,
} from '@ant-design/icons-vue'
import { onMounted, ref, computed } from 'vue'
import { getCommunityPostVoByIdUsingGet } from '@/api/communityPostController'
import { isBizLikedUsingGet, addLikeRecordUsingPost } from '@/api/likeRecordController'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import MarkdownIt from 'markdown-it'
import { RouterLink, useRouter } from 'vue-router'
// 引入API类型命名空间
import '@/api/typings.d.ts'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import CommentSection from '@/pages/CommentSection.vue'

const router = useRouter()

const loginUserStore = useLoginUserStore()
const loginUser = loginUserStore.loginUser

const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  breaks: true,
  highlight: function (str, lang) {
    return `<pre class="language-${lang}"><code>${str}</code></pre>`
  },
})

const props = defineProps({
  id: {
    type: [Number],
    required: true,
  },
})

const postVO = ref<API.CommunityPostVO>()
const isLiked = ref(false)

// 判断内容是否是HTML格式
const isHtmlContent = computed(() => {
  if (!postVO.value?.content) return false
  // 简单检测是否包含完整HTML标签，且不太像Markdown
  return /<\/?[a-z][\s\S]*>/i.test(postVO.value.content) && !isLikelyMarkdown(postVO.value.content)
})

// 判断内容是否是Markdown格式
const isMarkdownContent = computed(() => {
  if (!postVO.value?.content) return false
  return isLikelyMarkdown(postVO.value.content)
})

// 渲染Markdown内容
const renderedMarkdown = computed(() => {
  if (!postVO.value?.content) return ''
  return md.render(postVO.value.content)
})

// 判断文本是否可能是Markdown
function isLikelyMarkdown(text: string): boolean {
  // 检查常见的Markdown特征
  const markdownPatterns = [
    /^#+\s+.+$/m, // 标题 (# Title)
    /\[.+\]\(.+\)/, // 链接 [text](url)
    /!\[.+\]\(.+\)/, // 图片 ![alt](url)
    /^>\s+.+$/m, // 引用 (> quote)
    /^[-*+]\s+.+$/m, // 无序列表 (- item)
    /^[0-9]+\.\s+.+$/m, // 有序列表 (1. item)
    /^```[\s\S]*?```$/m, // 代码块 (```code```)
    /\*\*.+\*\*/, // 粗体 (**bold**)
    /\*.+\*/, // 斜体 (*italic*)
    /^---+$/m, // 分隔线 (---)
    /^#{1,6}\s+.+$/m, // 不同级别标题
    /~~.+~~/, // 删除线 (~~text~~)
    /^-\s+-\s+-+$/m, // 表格分隔线
  ]

  // 匹配到至少2个Markdown模式，则认为是Markdown
  return markdownPatterns.filter((pattern) => pattern.test(text)).length >= 2
}

// 格式化日期
const formatDate = (date?: string | Date) => {
  if (!date) return ''
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

const getPostVoById = async () => {
  const res = await getCommunityPostVoByIdUsingGet({ id: props.id }, {})
  if (res.data.code === 0) {
    postVO.value = res.data.data
  } else {
    message.error('获取详情失败')
  }
}

onMounted(() => {
  getPostVoById()
  isUserLiked()
})

// 用户交互状态
const userFavorited = ref(false)

// 点赞处理函数
const handleLike = async () => {
  try {
    const liked = !isLiked.value
    const requestData = {
      liked: liked,
      objType: 'POST',
      objectId: props.id, // 确保objectId是数字类型
    }

    console.log('发送点赞/取消点赞请求:', requestData)

    const res = await addLikeRecordUsingPost(requestData, {})

    console.log('点赞/取消点赞响应:', res)

    // 后端没有返回错误信息，我们认为操作成功
    isLiked.value = liked
    if (postVO.value) {
      if (liked) {
        postVO.value.likeCount = (postVO.value.likeCount || 0) + 1
      } else {
        postVO.value.likeCount = Math.max((postVO.value.likeCount || 0) - 1, 0)
      }
    }
    message.success(liked ? '点赞成功' : '已取消点赞')
  } catch (error) {
    console.error('点赞/取消点赞出错:', error)
    message.error('操作失败，请稍后再试')
  }
}

// 收藏处理函数
const handleFavorite = () => {
  userFavorited.value = !userFavorited.value
  if (postVO.value) {
    if (userFavorited.value) {
      postVO.value.favourCount = (postVO.value.favourCount || 0) + 1
    } else {
      postVO.value.favourCount = Math.max((postVO.value.favourCount || 0) - 1, 0)
    }
    // 实际项目中应该调用API更新收藏状态
  }
}

// 点击文章跳转到详情页
const handlePostClick = (id: number) => {
  window.open(`/community/postDetail/${id}`, '_blank');
  // router.replace({
  //   path: `/community/postDetail/${id}`,
  // })
}

// 滚动到评论区
const scrollToComments = () => {
  commentsRef.value?.scrollIntoView({ behavior: 'smooth' })
}

// 评论区引用
const commentsRef = ref<HTMLElement | null>(null)

// 当添加评论时更新评论计数
const handleCommentAdded = () => {
  if (postVO.value) {
    postVO.value.commentCount = (postVO.value.commentCount || 0) + 1
  }
}

const handleCommentDeleted = () => {
  if (postVO.value) {
    postVO.value.commentCount = (postVO.value.commentCount || 1) - 1;
  }
}


// 当前用户是否点赞了
const isUserLiked = async () => {
  try {
    console.log('查询点赞状态，objectId:', props.id)
    const res = await isBizLikedUsingGet({ objectId: props.id }, {})
    console.log('查询点赞状态响应:', res)

    if (res.data && res.data.code === 0) {
      isLiked.value = res.data.data || false
      console.log('当前点赞状态:', isLiked.value)
    } else {
      console.error('查询点赞状态失败:', res)
    }
  } catch (error) {
    console.error('查询点赞状态出错:', error)
  }
}

// 返回首页
const goHome = () => {
  router.push('/')
}
</script>

<style scoped>
.post-detail-container {
  max-width: 100%;
  min-height: 100vh;
  background-color: #f7f8fa;
}

/* 导航栏样式 */
.post-header {
  background: linear-gradient(to right, #f8f9fa, #f0f2f5);
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  padding: 0;
  position: sticky;
  top: 0;
  z-index: 100;
  border-bottom: 1px solid #eaeaea;
  height: 60px;
  display: flex;
  align-items: center;
}

.header-content {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 100%;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.breadcrumb {
  display: flex;
  justify-content: center;
  flex-direction: row;
  gap: 5px;
}

.logo {
  display: flex;
  align-items: center;
}

.logo-img {
  height: 32px;
  width: auto;
  cursor: pointer;
}

.community-name {
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  color: #1890ff;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
}

/* 主体内容样式 */
.post-content {
  max-width: 1200px;
  margin: 20px auto;
  display: grid;
  grid-template-columns: 60px 1fr 300px;
  gap: 20px;
  padding: 0 20px;
}

.post-top {
  margin-bottom: 20px;
}

.post-top-intro {
  color: #515a6e;
  font-size: 14px;
  font-family: PingFangSC-Regular;
  line-height: 16px;
}

.post-image {
  max-width: 100%;
  margin-top: 30px;
  margin-bottom: 30px;
  border-radius: 8px;
  display: block;
}

/* 左侧统计信息样式 */
.post-stats {
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.post-stats-sticky {
  position: sticky;
  top: 80px; /* 导航栏高度 + 额外间距 */
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  padding-top: 20px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid rgba(255, 255, 255, 0.6);
}

.avatar-large {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid rgba(255, 255, 255, 0.6);
  margin-bottom: 15px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  padding: 10px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.stat-item:hover {
  background-color: #f0f7ff;
  transform: translateY(-2px);
}

.stat-item .anticon {
  font-size: 20px;
  color: #8c8c8c;
  transition: all 0.3s ease;
}

.stat-item .anticon.liked {
  color: #ff4d4f;
}

.stat-item .anticon.favorited {
  color: #faad14;
}

.stat-value {
  font-size: 16px;
  font-weight: bold;
  margin: 5px 0;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

/* 中间文章内容样式 */
.post-main {
  background-color: #fff;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.post-other-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #333;
  cursor: pointer;
}

.post-other-title:hover {
  color: #1890ff;
}

.post-summary {
  font-size: 16px;
  color: #666;
  margin-bottom: 20px;
  line-height: 1.6;
}

.post-author {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.author-info {
  flex: 1;
  margin-left: 20px;
}

.author-name {
  font-weight: 500;
  margin-bottom: 5px;
}

.post-meta {
  font-size: 13px;
  color: #999;
  display: flex;
  gap: 15px;
}

.post-body {
  font-size: 16px;
  line-height: 1.8;
  color: #333;
  overflow-wrap: break-word;
}

/* HTML内容样式 */
.content-html {
  max-width: 100%;
}

.content-html img {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
  margin: 10px 0;
}

.content-html h1,
.content-html h2,
.content-html h3,
.content-html h4,
.content-html h5,
.content-html h6 {
  margin-top: 1.5em;
  margin-bottom: 0.5em;
  font-weight: 600;
  line-height: 1.25;
  color: #333;
}

.content-html p {
  margin-bottom: 1em;
}

.content-html pre {
  background-color: #f6f8fa;
  padding: 16px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 16px 0;
}

.content-html code {
  font-family: SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;
  font-size: 85%;
  background-color: rgba(27, 31, 35, 0.05);
  padding: 0.2em 0.4em;
  border-radius: 3px;
}

.content-html pre code {
  background-color: transparent;
  padding: 0;
}

.content-html blockquote {
  padding: 0 1em;
  color: #6a737d;
  border-left: 0.25em solid #dfe2e5;
  margin: 0 0 16px 0;
}

.content-html ul,
.content-html ol {
  padding-left: 2em;
  margin-bottom: 16px;
}

/* 纯文本内容样式 */
.content-text {
  font-family: inherit;
  background: none;
  border: none;
  padding: 0;
  margin: 0;
  overflow-wrap: break-word;
  white-space: pre-wrap;
  font-size: inherit;
  line-height: inherit;
  color: inherit;
}

/* 右侧作者信息样式 */
.post-sidebar {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.author-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  text-align: center;
}

.author-name-large {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 10px;
}

.author-bio {
  font-size: 14px;
  color: #666;
  margin-bottom: 15px;
}

.author-stats {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-bottom: 15px;
}

.stat {
  text-align: center;
}

.stat-value {
  font-size: 16px;
  font-weight: bold;
  display: block;
}

.stat-label {
  font-size: 12px;
  color: #999;
}

.follow-btn {
  width: 100%;
}

.related-posts {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.related-posts h3 {
  font-size: 16px;
  margin-bottom: 15px;
  color: #333;
}

.related-post-item {
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}


.related-post-item:last-child {
  border-bottom: none;
}

.related-post-item .post-title {
  font-size: 14px;
  margin-bottom: 5px;
  color: #333;
}

.related-post-item .post-meta {
  font-size: 12px;
  color: #999;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .post-content {
    grid-template-columns: 1fr;
  }

  .post-stats {
    display: none;
  }

  .post-sidebar {
    display: none;
  }
}

/* Markdown内容样式 */
.content-markdown {
  max-width: 100%;
}

.content-markdown img {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
  margin: 10px 0;
}

.content-markdown h1,
.content-markdown h2,
.content-markdown h3,
.content-markdown h4,
.content-markdown h5,
.content-markdown h6 {
  margin-top: 1.5em;
  margin-bottom: 0.5em;
  font-weight: 600;
  line-height: 1.25;
  color: #333;
}

.content-markdown h1 {
  font-size: 2em;
  border-bottom: 1px solid #eaecef;
  padding-bottom: 0.3em;
}

.content-markdown h2 {
  font-size: 1.5em;
  border-bottom: 1px solid #eaecef;
  padding-bottom: 0.3em;
}

.content-markdown h3 {
  font-size: 1.25em;
}

.content-markdown h4 {
  font-size: 1em;
}

.content-markdown p {
  margin-bottom: 1em;
}

.content-markdown pre {
  background-color: #f6f8fa;
  padding: 16px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 16px 0;
}

.content-markdown code {
  font-family: SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;
  font-size: 85%;
  background-color: rgba(27, 31, 35, 0.05);
  padding: 0.2em 0.4em;
  border-radius: 3px;
}

.content-markdown pre code {
  background-color: transparent;
  padding: 0;
}

.content-markdown blockquote {
  padding: 0 1em;
  color: #6a737d;
  border-left: 0.25em solid #dfe2e5;
  margin: 0 0 16px 0;
}

.content-markdown ul,
.content-markdown ol {
  padding-left: 2em;
  margin-bottom: 16px;
}

.content-markdown table {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 16px;
}

.content-markdown table th,
.content-markdown table td {
  padding: 8px;
  border: 1px solid #dfe2e5;
}

.content-markdown table th {
  background-color: #f6f8fa;
  font-weight: 600;
}

.content-markdown hr {
  height: 0.25em;
  padding: 0;
  margin: 24px 0;
  background-color: #e1e4e8;
  border: 0;
}

/* 提交按钮样式 */
:deep(.submit-button) {
  background: linear-gradient(135deg, #ff8e53 0%, #ff6b6b 100%);
  border: none;
  color: white;
  width: 150px;
  height: 40px;
  border-radius: 22px;
  font-size: 15px;
  font-weight: 500;
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.2);
  transition: all 0.3s ease;
}

:deep(.submit-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(255, 107, 107, 0.3);
}

:deep(.submit-button:active) {
  transform: translateY(1px);
}
</style>
